package main

import (
	"bufio"
	"bytes"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"os/exec"
	"sync"
	"time"
)

func main() {
	cmd := os.Args
	var pcmd *exec.Cmd
	if len(cmd) == 1 {
		os.Exit(1)
	} else if len(cmd) == 2 {
		pcmd = exec.Command(cmd[1])
	} else {
		pcmd = exec.Command(cmd[1], cmd[2:]...)
	}
	var log bytes.Buffer
	var wi bytes.Buffer
	mw := io.MultiWriter(os.Stdout, &log)
	pcmd.Stderr = mw
	pcmd.Stdout = mw
	pipe, _ := pcmd.StdinPipe() // = r //bufio.NewReader(xw)
	go func() {
		var mutex sync.Mutex //定义一个锁的变量(互斥锁的关键字是Mutex，其是一个结构体，传参一定要传地址，否则就不对了)

		http.HandleFunc("/cmd", func(w http.ResponseWriter, r *http.Request) {
			mutex.Lock()
			body, _ := ioutil.ReadAll(r.Body)
			wi.Write(body)
			log.Reset()
			pipe.Write(body)
			time.Sleep(time.Duration(200) * time.Millisecond)
			mutex.Unlock()
			data := make([]byte, 10240)
			len, _ := log.Read(data)
			w.Write(data[:len])
		})
		http.ListenAndServe("0.0.0.0:8001", nil)
	}()
	pcmd.Start()
	go func() {

		scanner := bufio.NewScanner(os.Stdin)
		for scanner.Scan() {
			pipe.Write(scanner.Bytes())
			pipe.Write([]byte("\n"))
		}
	}()
	pcmd.Wait()
	time.Sleep(time.Duration(100) * time.Millisecond)
}
